//
//  EMAddAddressViewController.m
//  ElectronicMall
//
//  Created by 史伟文 on 14/12/26.
//  Copyright (c) 2014年 cczu. All rights reserved.
//

#import "EMAddAddressViewController.h"
#import "UINavigationController+EMNavi.h"
#import "EMInputTextField.h"
#import "EMActionSheet.h"
#import "AppDelegate.h"
#import "MBProgressHUD.h"
#import "EMAddAddressReqBody.h"
#import "EMAddAddressRespBody.h"
#import "EMCityListReqBody.h"
#import "EMCityListRespBody.h"
#import "UserInfo.h"

@interface EMAddAddressViewController ()
{
//    EMInputTextField *areaTF;
    EMInputTextField *addressTF;
    EMInputTextField *aCodeTF;
    EMInputTextField *nameTF;
    EMInputTextField *phoneTF;
    
    EMActionSheet *actionSheet;
    UIButton *chooseAreaBtn;
    
    NSString *selectedProv;
    NSString *selectedCity;
    NSString *selectedArea;
    NSString *selectedProvCode;
    NSString *selectedCityCode;
    NSString *selectedAreaCode;
    UIPickerView *cityPickerView;
    
    AppDelegate *app;
    NSMutableArray *m_provArray;
    NSMutableArray *m_cityArray;
    NSMutableArray *m_areaArray;
    NSArray *provChildArray;
    NSArray *cityChildArray;
    NSArray *areaChildArray;
    
    EMCityListRespBody *addressData;
}
@end

@implementation EMAddAddressViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGB(242, 242, 242);
    [self.navigationController setNavigationMode:EMNavigationModeDefault andSubMode:0];
    self.navigationItem.title = @"添加地址";
    
    addressData = [[EMCityListRespBody alloc] init];
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame=CGRectMake(0, 0, 30, 32);
    [button setImage:[UIImage imageNamed:@"button_导航_返回_白"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem =[[UIBarButtonItem alloc]initWithCustomView:button];
    
}
- (void)backAction: (UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    app = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    [self addAddress];
    m_provArray = [[NSMutableArray alloc] init];
    m_cityArray = [[NSMutableArray alloc] init];
    m_areaArray = [[NSMutableArray alloc] init];
    UIImage *arrow = [UIImage imageNamed:@"icon_菜单_展开"];
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    scrollView.contentSize = CGSizeMake(W(320), H(800));
    
    int height = 25;

    UILabel *areaTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), 120, 30)];
    areaTitleLabel.text = @"收货地区";
    areaTitleLabel.textColor = [UIColor darkGrayColor];
    areaTitleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:areaTitleLabel];
    height += 20 + 5;
    chooseAreaBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    chooseAreaBtn.frame = CGRectMake(W(10), H(height), W(300), H(35));
    chooseAreaBtn.layer.borderColor = RGB(112, 179, 81).CGColor;
    chooseAreaBtn.layer.borderWidth = 1;
    chooseAreaBtn.layer.cornerRadius = 5;
    chooseAreaBtn.titleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    chooseAreaBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    chooseAreaBtn.contentEdgeInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    [chooseAreaBtn setTitle:@"请选择地区" forState:UIControlStateNormal];
    [chooseAreaBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    UIButton *but = [UIButton buttonWithType:UIButtonTypeSystem];
    but.frame = CGRectMake(chooseAreaBtn.frame.size.width - W(35), 0, W(35), H(35));
    [but setImage:[arrow imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] forState:UIControlStateNormal];
    but.layer.borderColor = RGB(112, 179, 81).CGColor;
    but.layer.borderWidth = 1;
    UIBezierPath *maskPath = [UIBezierPath bezierPathWithRoundedRect:but.bounds byRoundingCorners:UIRectCornerTopRight | UIRectCornerBottomRight cornerRadii:CGSizeMake(5, 5)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = but.bounds;
    maskLayer.path = maskPath.CGPath;
    but.layer.mask = maskLayer;
    [chooseAreaBtn addSubview:but];
    [chooseAreaBtn addTarget:self action:@selector(chooseArea:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:chooseAreaBtn];
    
    height += 30 + 10;
    UILabel *addressTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), 120, 30)];
    addressTitleLabel.text = @"详细地址";
    addressTitleLabel.textColor = [UIColor darkGrayColor];
    addressTitleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:addressTitleLabel];
    height += 20 + 5;
    addressTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    [addressTF setTextFieldMode:EMInputTextFieldModeText];
    addressTF.inputTextField.delegate = self;
    [scrollView addSubview:addressTF];
    
    height += 30 + 10;
    UILabel *aCodeTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), 120, 30)];
    aCodeTitleLabel.text = @"邮编";
    aCodeTitleLabel.textColor = [UIColor darkGrayColor];
    aCodeTitleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:aCodeTitleLabel];
    height += 20 + 5;
    aCodeTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    [aCodeTF setTextFieldMode:EMInputTextFieldModeText];
    aCodeTF.inputTextField.delegate = self;
    [scrollView addSubview:aCodeTF];
    
    height += 30 + 10;
    UILabel *nameTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), 120, 30)];
    nameTitleLabel.text = @"收货人";
    nameTitleLabel.textColor = [UIColor darkGrayColor];
    nameTitleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:nameTitleLabel];
    height += 20 + 5;
    nameTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    [nameTF setTextFieldMode:EMInputTextFieldModeText];
    nameTF.inputTextField.delegate = self;
    [scrollView addSubview:nameTF];
    
    height += 30 + 10;
    UILabel *phoneTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(W(10), H(height), 120, 30)];
    phoneTitleLabel.text = @"联系电话";
    phoneTitleLabel.textColor = [UIColor darkGrayColor];
    phoneTitleLabel.font = [UIFont fontWithName:HEITIMEDIUM size:14];
    [scrollView addSubview:phoneTitleLabel];
    height += 20 + 5;
    phoneTF = [[EMInputTextField alloc] initWithFrame:CGRectMake(W(10), H(height), W(300), H(35))];
    [phoneTF setTextFieldMode:EMInputTextFieldModeText];
    phoneTF.inputTextField.delegate = self;
    [scrollView addSubview:phoneTF];
    
    
    
    height += 30 + 30;
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    btn.frame = CGRectMake(W(10), H(height), W(300), H(40));
    btn.backgroundColor = RGB(112, 179, 81);
    btn.layer.cornerRadius = 5;
    btn.titleLabel.font = [UIFont boldSystemFontOfSize:20];
    [btn setTitle:@"确认地址" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(handupAddress:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:btn];
    [self.view addSubview:scrollView];
    
    
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapBackground:)];
    [self.view addGestureRecognizer:tapGR];
    
    
    cityPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(W(10), H(100), 280, 100)];
    cityPickerView.delegate = self;
    cityPickerView.dataSource = self;

    actionSheet =[[EMActionSheet alloc]initWithFrame:CGRectMake(0,[UIScreen mainScreen].bounds.size.height , [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
    [actionSheet initWithTitle:@"查询类型" andContentView:cityPickerView];
    
    UIButton *chooseCityBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    chooseCityBtn.frame = CGRectMake(W(255), [UIScreen mainScreen].bounds.size.height - H(250), W(50), H(30));
    chooseCityBtn.backgroundColor = RGB(112, 179, 81);
    chooseCityBtn.layer.cornerRadius = 5;
    chooseCityBtn.titleLabel.font = [UIFont boldSystemFontOfSize:14];
    [chooseCityBtn setTitle:@"选好了" forState:UIControlStateNormal];
    [chooseCityBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [chooseCityBtn addTarget:self action:@selector(confirmChooseAction:) forControlEvents:UIControlEventTouchUpInside];
    [actionSheet addSubview:chooseCityBtn];
    
    provChildArray = addressData.SUCCESSFULINFO;
    for (int i = 0; i < addressData.SUCCESSFULINFO.count; i ++) {
        NSDictionary *provModel = @{@"provName":provChildArray[i][@"name"],
                                    @"provCode":provChildArray[i][@"id"],
                                    @"provChild":provChildArray[i][@"child"]};
        [m_provArray addObject:provModel];
    }

    cityChildArray = provChildArray[0][@"child"];
    for (int i = 0; i < cityChildArray.count; i ++) {
        NSDictionary *cityModel = @{@"cityName":cityChildArray[i][@"name"],
                                    @"cityCode":cityChildArray[i][@"id"],
                                    @"cityChild":cityChildArray[i][@"child"]};
        [m_cityArray addObject:cityModel];
    }
    
    areaChildArray = cityChildArray[0][@"child"];
    for (int i = 0; i < areaChildArray.count; i ++) {
        NSDictionary *areaModel = @{@"areaName":areaChildArray[i][@"name"],
                                    @"areaCode":areaChildArray[i][@"id"]};
        [m_areaArray addObject:areaModel];
    }
}
#pragma mark - picker view delegate
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 3;
}
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (component == 0) {
        return m_provArray.count;
    } else if (component == 1){
        return m_cityArray.count;
    } else {
        if (m_areaArray.count != 0) {
            return m_areaArray.count;
        } else {
            return 0;
        }
        
    }
}
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return m_provArray[row][@"provName"];
    } else if (component == 1){
        return m_cityArray[row][@"cityName"];
    } else {
        return m_areaArray[row][@"areaName"];
    }
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        [m_areaArray removeAllObjects];
        [m_cityArray removeAllObjects];
        cityChildArray = provChildArray[row][@"child"];
        for (int i = 0; i < cityChildArray.count; i ++) {
            NSDictionary *cityModel = @{@"cityName":cityChildArray[i][@"name"],
                                        @"cityCode":cityChildArray[i][@"id"],
                                        @"cityChild":cityChildArray[i][@"child"]};
            [m_cityArray addObject:cityModel];
        }

        [pickerView selectRow:0 inComponent:1 animated:YES];
        [pickerView reloadComponent:1];
        areaChildArray = cityChildArray[0][@"child"];
        for (int i = 0; i < areaChildArray.count; i ++) {
            NSDictionary *areaModel = @{@"areaName":areaChildArray[i][@"name"],
                                        @"areaCode":areaChildArray[i][@"id"]};
            [m_areaArray addObject:areaModel];
        }
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [pickerView reloadComponent:2];
    } else if (component == 1) {
        [m_areaArray removeAllObjects];
        areaChildArray = cityChildArray[row][@"child"];
        for (int i = 0; i < areaChildArray.count; i ++) {
            NSDictionary *areaModel = @{@"areaName":areaChildArray[i][@"name"],
                                        @"areaCode":areaChildArray[i][@"id"]};
            [m_areaArray addObject:areaModel];
        }
        
        [pickerView selectRow:0 inComponent:2 animated:YES];
        [pickerView reloadComponent:2];
    }
    
}
#pragma mark - 关闭键盘
- (void)tapBackground:(UIGestureRecognizer *)recog
{
    [self closeKeyboard];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self closeKeyboard];
    return NO;
}

- (void)closeKeyboard
{
    [addressTF.inputTextField resignFirstResponder];
    [aCodeTF.inputTextField resignFirstResponder];
    [nameTF.inputTextField resignFirstResponder];
    [phoneTF.inputTextField resignFirstResponder];
}
#pragma mark - 点击事件
- (void)chooseArea:(UIButton *)sender
{
    [UIView animateWithDuration:0.3 animations:^{
        actionSheet.frame =CGRectMake(0,0 ,[UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        [self.navigationController.view addSubview:actionSheet];
    }];
}
- (void)confirmChooseAction:(UIButton *)sender
{
    [actionSheet removeActionSheet];
    NSInteger row1 =[cityPickerView selectedRowInComponent:0];
    NSMutableString *selected1 = m_provArray[row1][@"provName"];
    NSInteger row2 =[cityPickerView selectedRowInComponent:1];
    NSMutableString *selected2 = m_cityArray[row2][@"cityName"];
    NSInteger row3 =[cityPickerView selectedRowInComponent:2];
    NSString *selected3;
    if ([m_areaArray count] == 0) {
        selected3 = @"";
    } else {
        selected3 = m_areaArray[row3][@"areaName"];
    }
    
    NSString *message = [[NSString alloc] initWithFormat:@"%@%@%@",selected1,selected2,selected3];
    [chooseAreaBtn setTitle:message forState:UIControlStateNormal];
    NSLog(@"你选择的是:%@%@%@",selected1,selected2,selected3);
    
    selectedProv = m_provArray[row1][@"provName"];
    selectedCity = m_cityArray[row2][@"cityName"];
    selectedArea = m_areaArray[row3][@"areaName"];
    selectedProvCode = m_provArray[row1][@"provCode"];
    selectedCityCode = m_cityArray[row2][@"cityCode"];
    selectedAreaCode = m_areaArray[row3][@"areaCode"];
    
    
}

- (void)handupAddress:(UIButton *)sender
{
    if ([addressTF.inputTextField.text isEqualToString:@""] || addressTF.inputTextField.text == nil) {
        [app showTip:@"请输入具体地址"];
        return;
    }
    if ([aCodeTF.inputTextField.text isEqualToString:@""] || aCodeTF.inputTextField.text == nil) {
        [app showTip:@"请输入邮编"];
        return;
    }
    if ([nameTF.inputTextField.text isEqualToString:@""] || nameTF.inputTextField.text == nil) {
        [app showTip:@"请输入姓名"];
        return;
    }
    if ([phoneTF.inputTextField.text isEqualToString:@""] || phoneTF.inputTextField.text == nil) {
        [app showTip:@"请输入手机号"];
        return;
    }
    if (aCodeTF.inputTextField.text.length != 6) {
        [app showTip:@"邮编位数不对"];
        return;
    }
    
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMAddAddressReqBody *reqBody = [[EMAddAddressReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"ADD-NEW-ADDRESS";
    reqBody.UID = [UserInfo sharedUserInfo].m_userName;
    reqBody.SESSION = [UserInfo sharedUserInfo].m_session;
    reqBody.NAME = nameTF.inputTextField.text;
    reqBody.PROVINCE = selectedProvCode;
    reqBody.CITY = selectedCityCode;
    reqBody.AREA = selectedAreaCode;
    reqBody.PRONAME = selectedProv;
    reqBody.CITYNAME = selectedCity;
    reqBody.AREANAME = selectedArea;
    reqBody.CODE = aCodeTF.inputTextField.text;
    reqBody.STREET = addressTF.inputTextField.text;
    reqBody.TEL = phoneTF.inputTextField.text;
    
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMAddAddressRespBody *respBody = [EMAddAddressRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        NSLog(@"%@", respInfo);
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            [app showTip:respBody.SUCCESSFULINFO];
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];

    
}

- (void)addAddress
{
    [MBProgressHUD  showHUDAddedTo:self.navigationController.view animated:YES];
    EMCityListReqBody *reqBody = [[EMCityListReqBody alloc] init];
    reqBody.JUDGEMETHOD = @"GET-PRO-CITY-AREA";
    HessianFormDataRequest *request = [[HessianFormDataRequest alloc] init];
    request.postData = reqBody.keyValues;
    [request startRequestWithURL:baseURL andCompletionBlcok:^(NSDictionary *respInfo) {
        EMCityListRespBody *respBody = [EMCityListRespBody objectWithKeyValues:respInfo];
        [MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
        if ([respBody.ERRORCODE isEqualToString: @"0000"]) {
            
            addressData = respBody;
            
        } else {
            [app showTip:respInfo[@"ERRORDESTRIPTION"]];
        }
        
    } andFailedBlock:^{
        
        [app showTip:@"无法连接服务器、请稍后再试"];
    }];
    
    
    
    
    
}

- (void)showAlert:(NSString *)content
{
    EMAttention *attention = [[EMAttention alloc] initWithTitle:@"提示" contentText:content leftButtonTitle:nil rightButtonTitle:@"确定"];
    [attention show];
}
@end
